package com.qdxwx.web.controller.live;


import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.data.service.course.CourseNodeService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.course.CourseStudyHistoryService;
import com.qdxwx.data.service.favorite.FavoriteService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.data.service.user.UserBuyService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.course.CourseDTO;
import com.qdxwx.models.course.CourseNode;
import com.qdxwx.models.course.CourseStudyHistory;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.enums.WebsiteProfileType;
import com.qdxwx.models.member.MemberType;
import com.qdxwx.models.teacher.Teacher;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 直播接口
 * @author developer
 */
@Controller
@RequestMapping("/live")
public class LiveViewController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(LiveViewController.class);
	@Autowired
	private CourseService courseService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private CourseNodeService courseNodeService;
	@Autowired
	private UserBuyService userBuyService;
	@Autowired
	private FavoriteService favoriteService;
	@Autowired
	private CourseStudyHistoryService courseStudyHistoryService;
	@Autowired
	private MemberTypeService memberTypeService;
	@Autowired
	private WebsiteProfileService websiteProfileService;
	@Autowired
	private UserService userService;

	/**
	 * 直播详情
	 */
	@GetMapping("/view/{id:[0-9]+}.html")
	public String liveInfo(HttpServletRequest request,
						   @PathVariable("id") int courseId,
						   ModelMap model) {
		// 查询详情
		Course course = courseService.get(courseId);
		if (course == null) {
			return VIEW_ERROR_404;
		}
		//查询目录
		List<CourseNode> courseNodeTree = courseNodeService.getTreeByCourseId(courseId);
		/*最近开始直播的章节*/
		CourseNode courseNode = new CourseNode();
		model.put("courseNode", courseNode);

		model.put("courseNodeTree", courseNodeTree);

		model.put("course", course);
		//更新课程的浏览量
		courseService.updateView(courseId);

		//查询课程老师
		List<Teacher> teacherList = teacherService.getListByCourseId(courseId);
		model.put("teacherList", teacherList);
		//相关课程
		List<CourseDTO> courseList = courseService.getInterfixList(course, 5);
		for (CourseDTO courseDTO : courseList) {
			teacherList = teacherService.getListByCourseId(courseDTO.getCourseId());
			courseDTO.setTeacherList(teacherList);
		}
		model.put("courseList", courseList);
		User user = LoginUser.getUser(request);
		//判断该课程是否可以观看
		if (user != null) {
			//判断该课程是否可以观看
			boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.COURSE.ordinal(),courseId);
			//查询是否已经收藏
			boolean isFavorite = favoriteService.isExist(user.getUserId(), courseId, ModuleType.COURSE.ordinal());
			model.put("isFavorite", isFavorite);
			model.put("isBuy", isBuy);
			//查询课程最近被观看到章节
			if (isBuy) {
				CourseStudyHistory lastTimeStudyHistory = courseStudyHistoryService.getLastByUserId(user.getUserId(), courseId);
				model.put("lastTimeStudyHistory", lastTimeStudyHistory);
			}
		} else {
			model.put("isFavorite", false);
			model.put("isBuy", false);
		}

		Map<String, Object> serviceSwitch = websiteProfileService.getMap(WebsiteProfileType.serviceSwitch.toString());
		if ("ON".equals(serviceSwitch.get("member")) && ObjectUtils.isNotNull(memberTypeService)) {
			/*查询课程对应的会员类型*/
			List<MemberType> memberTypes = memberTypeService.getListByCourseId(courseId);
			model.put("memberTypes", memberTypes);
		}

		//如果是直播查询 未开始的（开始了默认学过）节点数量
		CourseNode query = new CourseNode();
		query.setCourseId(course.getCourseId());
		query.setLiveBeginTime(LocalDateTime.now());
		long notStart = courseNodeService.count(query);
		int videoNodeSize = courseNodeService.countVideo(course.getCourseId());
		/*已开始开始的直播节点数量*/
		model.put("started", videoNodeSize - notStart);
		//课程视频节点的 总数
		model.put("videoNodeSize", videoNodeSize);


		int learnedUserCount = userBuyService.countByCourseId(courseId);

		model.put("learnedUserCount", learnedUserCount);
		if (learnedUserCount > 0) {
			//学习此课程的人 (最新8个)
			@SuppressWarnings("unchecked")
			List<User> learnedUsers = (List<User>) CacheUtils.get(CacheConstants.COURSE_LEARNED_PREFIX + "course" + courseId);
			if (learnedUsers == null || learnedUsers.size() == 0) {
				learnedUsers = userService.getLatelyStudentList(courseId, 8);

				CacheUtils.set(CacheConstants.COURSE_LEARNED_PREFIX + "course" + courseId, learnedUsers, 6000);//缓存5分钟
			}
			model.put("learnedUsers", learnedUsers);
		}
		return getViewPath("live/live-infor");

	}
}